package cz.proks.schoolpupilbook.gwt.core.handler;

import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;

import cz.proks.schoolpupilbook.gwt.core.CookieHelper;
import cz.proks.schoolpupilbook.gwt.core.ResultNotifiable;
import cz.proks.schoolpupilbook.gwt.service.ServiceFactory;
import cz.proks.schoolpupilbook.gwt.service.UserService;
import cz.proks.schoolpupilbook.gwt.widget.common.UserForm;
import cz.proks.schoolpupilbook.shared.Constants;
import cz.proks.schoolpupilbook.shared.domain.User;

public class UserFormHandler implements UserForm.SubmitEvent.SubmitEventHandler {

	@Override
	public void onSubmit(UserForm.SubmitEvent event) {
		UserService userService = ServiceFactory.getUserService();
		final User user = createUser(event);
		
		userService.save(user, new ResultNotifiable<Void>() {
			
			@Override
			public void onSucces(Void object) {
				if (isLoggedUser(user))
					updateLoggedUser(user);
				
				History.back();
			}
			
			@Override
			public void onError(Throwable t) {
				Window.alert("Failed to save user: " + t.getLocalizedMessage());
			}
		});
	}
	
	private User createUser(UserForm.SubmitEvent event) {
		User user = new User();
		
		user.setId(event.getId());
		user.setName(event.getName());
		user.setSurname(event.getSurname());
		user.setRole(event.getRole());
		user.setUsername(event.getUsername());
		user.setPassword(event.getPassword());
				
		return user;
	}
	
	private boolean isLoggedUser(User user) {
		User loggedUser = CookieHelper.getLoggedUser();
		if (loggedUser != null && user != null && 
			loggedUser.getId().equals(user.getId())) 
			return true;
		
		return false;		
	}
	
	private void updateLoggedUser(User user) {
		String cookie = CookieHelper.asCookie(user);
		Cookies.setCookie(Constants.Cookie.USER, cookie);
	}
}
